package com.winspread.app.paging

import android.os.Bundle
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.winspread.app.R
import com.winspread.app.databinding.ActivityPagingBinding
import com.winspread.mvvm.base.vm.BaseActivity
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 仿  https://blog.csdn.net/guolin_blog/article/details/114707250
 *
 * @property pagingVm PagingMV
 * @property repoAdapter RepoAdapter
 */

@AndroidEntryPoint
class PagingActivity : BaseActivity<PagingMV, ActivityPagingBinding>(R.layout.activity_paging) {


    init {
        //关闭沉浸式
        initImmersionBar(statusBarFont = true, isBar = false)
    }

    @Inject
    lateinit var pagingVm:PagingMV

    @Inject
    lateinit var repoAdapter: RepoAdapter

    override fun initView() {
        binding.recyclerView.apply {
           layoutManager = LinearLayoutManager(this@PagingActivity)
            adapter = repoAdapter.withLoadStateFooter(FooterAdapter{
                repoAdapter.retry()
            })
        }
    }

    override fun initData(extras: Bundle?) {
        lifecycleScope.launch {
            pagingVm.getPagingData().collect{
                repoAdapter.submitData(it)
            }
        }

    }


    override fun initListenter() {
        repoAdapter.addLoadStateListener {
            when(it.refresh){
                is LoadState.NotLoading->{
                    binding.progressBar.visibility = View.INVISIBLE
                    binding.recyclerView.visibility = View.VISIBLE
                }
                is LoadState.Loading->{
                    binding.progressBar.visibility = View.VISIBLE
                    binding.recyclerView.visibility = View.INVISIBLE
                }
                is LoadState.Error->{
                  val state =   it.refresh as LoadState.Error
                    binding.progressBar.visibility = View.INVISIBLE
                    ToastUtils.showShort("Load Error: ${state.error.message}")
                }
            }


        }

    }



}